<template>
  <div class="user-profile">
    <el-form 
      ref="profileFormRef"
      :model="profileForm" 
      :rules="profileRules"
      label-width="100px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="profileForm.username" disabled />
      </el-form-item>
      
      <el-form-item label="真实姓名" prop="name">
        <el-input v-model="profileForm.name" placeholder="请输入真实姓名" />
      </el-form-item>
      
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="profileForm.phone" placeholder="请输入手机号码" />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="profileForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="出生日期" prop="birthDate">
        <el-date-picker
          v-model="profileForm.birthDate"
          type="date"
          placeholder="选择出生日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="profileForm.address"
          type="textarea"
          :rows="2"
          placeholder="请输入地址"
        />
      </el-form-item>

      <!-- 医生特有字段 -->
      <template v-if="isDoctor">
        <el-form-item label="职称" prop="title">
          <el-select v-model="profileForm.title" placeholder="请选择职称">
            <el-option label="主任医师" value="1" />
            <el-option label="副主任医师" value="2" />
            <el-option label="主治医师" value="3" />
            <el-option label="住院医师" value="4" />
            <el-option label="实习医师" value="5" />
          </el-select>
        </el-form-item>

        <el-form-item label="学历" prop="education">
          <el-select v-model="profileForm.education" placeholder="请选择学历">
            <el-option label="博士" value="1" />
            <el-option label="硕士" value="2" />
            <el-option label="本科" value="3" />
            <el-option label="大专" value="4" />
            <el-option label="其他" value="5" />
          </el-select>
        </el-form-item>
      </template>
      
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="avatar-uploader"
          action="/api/file/upload/avatar"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="profileForm.avatar" :src="baseUrl + profileForm.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
        保存
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { updateUserInfoApi, adminUpdateUserInfoApi } from '@/api/user'

const userStore = useUserStore()
const emit = defineEmits(['close'])

// 响应式数据
const submitLoading = ref(false)
const profileFormRef = ref()

// 计算属性
const isDoctor = computed(() => userStore.userInfo?.role === 2)
const isAdmin = computed(() => userStore.userInfo?.role === 3)
const baseUrl = import.meta.env.VITE_API_BASE_URL
// 表单数据
const profileForm = reactive({
  id: '',
  username: '',
  name: '',
  phone: '',
  email: '',
  gender: null,
  birthDate: '',
  address: '',
  avatar: '',
  role: null,
  title: '',
  education: ''
})

// 表单验证规则
const profileRules = {
  name: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 初始化个人信息
const initUserProfile = () => {
  const userInfo = userStore.userInfo
  if (userInfo) {
    Object.assign(profileForm, {
      id: userInfo.id,
      username: userInfo.username,
      name: userInfo.name || '',
      phone: userInfo.phone || '',
      email: userInfo.email || '',
      gender: userInfo.gender || null,
      birthDate: userInfo.birthDate || '',
      address: userInfo.address || '',
      avatar: userInfo.avatar || '',
      role: userInfo.role,
      title: userInfo.title || '',
      education: userInfo.education || ''
    })
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await profileFormRef.value.validate()
    submitLoading.value = true
    
    // 根据用户角色选择不同的更新方法
    const updateMethod = isAdmin.value ? adminUpdateUserInfoApi : updateUserInfoApi
    const response = await updateMethod(profileForm)
    
    if (response.code === 200) {
      ElMessage.success('个人信息更新成功')
      // 更新store中的用户信息
      userStore.setUserInfo(response.data)
      emit('close', 'success')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新个人信息失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  emit('close', 'cancel')
}

// 头像上传相关方法
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    profileForm.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error('头像上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

// 生命周期
onMounted(() => {
  initUserProfile()
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style> 